package bancosys.tec.services.input.driver;

import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;

import jmine.tec.services.io.ServiceBean;
import jmine.tec.services.io.ServicesPageBean;
import jmine.tec.services.io.ServicesWriter;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * ServiceWriter que escreve no formato XML.
 * 
 * @author Rafael Volpato
 */
public class XMLServiceWriter implements ServicesWriter {

    private static final String UTF8 = "UTF-8";

    /**
     * {@inheritDoc}
     */
    public void writeServices(List<ServicesPageBean> servicesPages, OutputStream outputStream) {
        ServicesPageCollection collection = new ServicesPageCollection();

        // Escrever no writer apenas as paginas que possuem serviços
        for (ServicesPageBean servicesPageBean : servicesPages) {
            if (servicesPageBean == null) {
                continue;
            }

            if ((servicesPageBean.getServices() != null) && (servicesPageBean.getServices().size() > 0)) {
                collection.addSheet(servicesPageBean);
            }
        }

        XStream xstream = new XStream(new DomDriver(UTF8));
        xstream.alias("service", ServiceBean.class);
        xstream.autodetectAnnotations(true);
        xstream.toXML(collection, outputStream);
    }

    /**
     * Classe auxiliar para fazer com que o XML gerado seja compativel com o XML esperado pelo driver de leitura.
     * 
     * @author Rafael Volpato
     * @date Nov 6, 2009
     */
    @XStreamAlias("importacao")
    private static class ServicesPageCollection {

        @XStreamImplicit
        private List<ServicesPageBean> workSheets = new LinkedList<ServicesPageBean>();

        /**
         * Adiciona um ServicePageBean a lista.
         * 
         * @param bean servicePageBean que será adicionado a lista
         */
        public void addSheet(ServicesPageBean bean) {
            this.workSheets.add(bean);
        }
    }
}
